package com.gsoft.browsertest;

import java.lang.String;
import java.lang.System;

import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
import android.content.ComponentName;
import 	android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebStorage;
import  android.graphics.Bitmap;
import android.net.WebAddress;
import android.os.Debug;
import android.os.Process;
import android.os.SystemClock;
import android.os.Handler;
import android.os.Message;
import android.widget.FrameLayout;
import android.webkit.WebIconDatabase;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings.TextSize;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebSettingsClassic;
import android.webkit.WebSettingsClassic.AutoFillProfile;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewDatabase;
import android.content.pm.PackageManager;
import android.content.pm.IPackageDataObserver;
import android.webkit.CacheManager;
import java.io.File;


public class testpage extends Activity {
    private String TAG = "Testpage";

    public static String extraname = "TestPageNum";

    public static int PageNum = 0;
    public WebView webview = null;
    PackageManager pkgmgr = null;

    public long startime = 0;
    public long endtime = 0;
    public long totaltime = 0;

    public FrameLayout rootLayout = null;

    private static final String IPAD_USERAGENT = "Mozilla/5.0 (iPad; " +
	"CPU OS 5_0_1 like Mac OS X) AppleWebKit/534.46 "	+
	"(KHTML, like Gecko) Version/5.1 Mobile/9A405 Safari/7534.48.3";


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        rootLayout = (FrameLayout)findViewById(R.id.FrameLayout01);
        PageNum = getIntent().getIntExtra(extraname,0);
        sendStartMsg(PageNum);
        pkgmgr = (PackageManager)this.getPackageManager();
    }

    protected void onResume() {
        super.onResume();
    }

    protected void onPause(){
        super.onPause();
    }

    public class CustomerChromeClient extends WebChromeClient{
        public void onProgressChanged(WebView view, int newProgress){
            super.onProgressChanged(view,newProgress);
            long cur = System.currentTimeMillis();
            Log.d(TAG,"Page "+PageNum+" progress "+newProgress+" at time "+cur);
            if(newProgress == 100){
                sendEndMsg();
            }
        }

        public void onReachedMaxAppCacheSize(long requiredStorage, long quota,
            WebStorage.QuotaUpdater quotaUpdater) {
            super.onReachedMaxAppCacheSize(requiredStorage,quota,quotaUpdater);
            Log.d(TAG,"onReachedMaxAppCacheSize " );
        }

    };

    public class CustomerClient extends WebViewClient{
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view,url);
            Log.d(TAG,"Page "+PageNum+" load resource "+url);
        }

        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view,url,favicon);
            Performance.tracePageStart(url);
            Performance.onPageStarted();
        }

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view,url);
            sendEndMsg();
            Performance.onPageFinished(url);
            Performance.tracePageFinished();
            
        }


    };

    

    public static final int TEST_START = 0;
    public static final int TEST_END = 1;
    public static final int TEST_CLEAN = 2;
    
    public static final int TEST_CLEAN2 = 3;

    public int testEnd = 0;

    public void sendStartMsg(int pgno){
        Message startmsg = new Message();
        startmsg.what = TEST_START;
        startmsg.arg1 = pgno;
        mainhandler.sendMessageDelayed(startmsg,3000);
    }

    public void sendEndMsg(){
        mainhandler.sendEmptyMessage(TEST_END);
    }



    public Handler mainhandler = new Handler() {
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch(msg.what) {
                case TEST_START:

                    webview = new WebView(testpage.this);
                    rootLayout.addView(webview);
                    webview.loadUrl("http://www.zol.com.cn/index.html");
                    webview.setWebChromeClient(new CustomerChromeClient());
                    webview.setWebViewClient(new CustomerClient());
                    webview.getSettings().setJavaScriptEnabled(true);
                    webview.getSettings().setPluginsEnabled(true);

                    webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
                    webview.getSettings().setUserAgentString(IPAD_USERAGENT);

                    startime = System.currentTimeMillis();
                    Log.d(TAG," START TEST #"+PageNum+" with view "+webview+" at time "+startime);
                    testEnd = 0;
                    break;
                case TEST_END:
                    if(testEnd >= 1){
                        endtime =  System.currentTimeMillis();
                        totaltime = endtime-startime;
                        Log.d(TAG,"page "+PageNum+" load total time "+totaltime);
                        webview.stopLoading();
                        webview.setPictureListener(null);
                        webview.onPause();
                        mainhandler.sendEmptyMessageDelayed(TEST_CLEAN,1000);
                    }else{
                        testEnd ++;
                    }
                    break;
                case TEST_CLEAN:
                    WebIconDatabase.getInstance().removeAllIcons();
                    webview.clearCache(true);
                    WebStorage.getInstance().deleteAllData();
                    webview.clearHistory();
                    webview.clearFormData();
                    mainhandler.sendEmptyMessageDelayed(TEST_CLEAN2,3000);
                    break;
                case TEST_CLEAN2:
                {
                    rootLayout.removeView(webview);
                    webview.destroy();
                    webview = null;
                    System.gc();

                    File file = CacheManager.getCacheFileBaseDir(); 
                    if (file != null && file.exists() && file.isDirectory()) { 
                        for (File item : file.listFiles()) { 
                            item.delete(); 
                        } 
                        file.delete(); 
                    } 
                    testpage.this.deleteDatabase("webview.db"); 
                    testpage.this.deleteDatabase("webviewCache.db");

/*
                    //start a new test
                    if(PageNum < 10){
                        PageNum++;
                        sendStartMsg(PageNum);
                    }
*/
                    int relttime = (int)totaltime;
                    testpage.this.setResult(relttime);
                    testpage.this.finish();
                }
                    break;
                default:
                    break;
            }
        }
    };








///==============
    public void startNewTestPage(){
        Intent startintent = new Intent();
        startintent.setComponent(new ComponentName("com.gsoft.browsertest","com.gsoft.browsertest.testpage"));
        startintent.putExtra(extraname,PageNum+1);
        startActivity(startintent);
    }


  
}

